package cn.geminis.lowcode.compiler;

import cn.geminis.lowcode.LcException;

/**
 * @author puddi
 */
public class LcModule {

    private static boolean initialed = false;

    private LcModule() {
    }

    /**
     * Useful from jdk9 and up; required from jdk16 and up. This code is supposed to gracefully do nothing on jdk8 and below, as this operation isn't needed there.
     */
    public static void addOpensForLombok() {
        if (!initialed) {
            ModuleLayer.boot().findModule("jdk.compiler")
                    .ifPresent(jdkCompilerModule -> {
                        String[] allPkgs = {
                                "com.sun.tools.javac.code",
                                "com.sun.tools.javac.comp",
                                "com.sun.tools.javac.file",
                                "com.sun.tools.javac.main",
                                "com.sun.tools.javac.model",
                                "com.sun.tools.javac.parser",
                                "com.sun.tools.javac.processing",
                                "com.sun.tools.javac.tree",
                                "com.sun.tools.javac.util",
                                "com.sun.tools.javac.jvm",
                        };
                        try {
                            var implAddOpensMethod = Module.class.getDeclaredMethod("implAddOpens", String.class);
                            implAddOpensMethod.setAccessible(true);
                            for (String pkg : allPkgs) {
                                implAddOpensMethod.invoke(jdkCompilerModule, pkg);
                            }
                        } catch (Exception e) {
                            throw new LcException("开放JDK内部方法异常", e);
                        }
                    });
            initialed = true;
        }
    }
}
